package org.tinygroup.ratelimitweblayer;

import java.io.IOException;

import javax.servlet.ServletException;

import org.tinygroup.commons.tools.StringUtil;
import org.tinygroup.weblayer.AbstractTinyFilter;
import org.tinygroup.weblayer.WebContext;

import com.google.common.util.concurrent.RateLimiter;

public class RateLimitFilter extends AbstractTinyFilter{
	private final static String RATE_LIMIT = "rate_limit";
	private  RateLimiter rateLimiter;

	public void preProcess(WebContext context) throws ServletException,
			IOException {
		if(rateLimiter!=null&&!rateLimiter.tryAcquire()){
			String characterEncoding = context.getRequest().getCharacterEncoding();
			context.getResponse().getOutputStream().write("达到流量限制".getBytes(characterEncoding));
		}
		
	}

	public void postProcess(WebContext context) throws ServletException,
			IOException {
		// TODO Auto-generated method stub
		
	}

	protected void customInit() {
		String connLimitValue = get(RATE_LIMIT);
		if(StringUtil.isBlank(connLimitValue)){
			return;
		}
		rateLimiter = RateLimiter.create(Double.parseDouble(connLimitValue));
	}

}
